
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:safetymonitor/app/components/common/no_permissions_widget.dart';
import 'package:safetymonitor/app/components/custom_modele/custom_cardx.dart';
import 'package:safetymonitor/app/core/core.dart';
import 'package:safetymonitor/app/core/ext/time.dart';
import 'package:safetymonitor/app/core/ext/widget_extension.dart';
import 'package:safetymonitor/app/core/http/http.dart';
import 'package:safetymonitor/app/core/utils/interface.dart';
import 'package:safetymonitor/app/core/utils/user_manager.dart';
import 'package:safetymonitor/app/data/entities/home/duty/duty_mgmt_day_entity.dart';
import 'package:safetymonitor/app/data/entities/home/duty/get_flood_prevention_data_by_duty_entity.dart';
import 'package:safetymonitor/app/data/entities/home/duty/major_event_entity.dart';
import 'package:safetymonitor/app/data/entities/home/duty/month_duty_date_entity.dart';
import 'package:safetymonitor/app/data/entities/home/duty/schedule_time_entity.dart';
import 'package:safetymonitor/generated/assets.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:url_launcher/url_launcher_string.dart';

part 'paint.dart';

part 'misc.dart';

part 'iface.dart';

/// 值班记录
final class DutyRecordPage extends StatefulWidget {
  const DutyRecordPage({super.key});

  @override
  State<DutyRecordPage> createState() => _DutyRecordPageState();
}

final class _DutyRecordPageState extends State<DutyRecordPage> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;
  late final _selectedDate = ValueNotifier<DateTime>(DateTime.now())..addListener(_refresh);
  CalendarFormat _calendarFormat = CalendarFormat.week;

  /// 事件列表
  List<EventModel> eventsList = [];

  final ScrollController _scrollController = ScrollController();

  /// 加载指定日期的事件
  List<EventModel> _loadEventsForDay(DateTime date) {
    print('datedate${date.toString()}');
    return eventsList.where((event) => event.date.year == date.year && event.date.month == date.month && event.date.day == date.day).toList();
  }

  bool curry = false;

  @override
  void initState() {
    _refresh();
    getMonthEvent(DateTime.now()).then((monthEvent) {
      eventsList = monthEvent;
      for (var i = 0; i < monthEvent.length; i++) {
        if (isSameDay(monthEvent[i].date, DateTime.now())) {
          curry = true;
        } else {
          curry = false;
        }
      }
      setState(() {});
      // 定位到该月第一个事件
      // if (eventsList.isNotEmpty) {
      //   _selectedDate.value = eventsList.first.date;
      // }
    });
    super.initState();

    ///当ListView滑动时的监听
    // _scrollController.addListener(() {
    //   //只要滑动就收缩
    //   if (_scrollController.offset >= _scrollController.position.minScrollExtent) {
    //     if (_calendarFormat == CalendarFormat.month) {
    //       _calendarFormat = CalendarFormat.week;
    //       setState(() {});
    //     }
    //   }
    // });
  }

  @override
  void dispose() {
    _selectedDate.dispose();
    _scrollController.dispose();
    _dutyList.value.clear();
    _majorEvent.value.clear();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ListenableBuilder(
      listenable: isNotPermissions,
      builder: (_, __) {
        if (!isNotPermissions.value) {
          return const NoPermissionsWidget(boolTOP: false);
        }
        return Scaffold(
          // appBar: CustomAppBar(
          //   title: Text(
          //     '值班管理',
          //     style: TextStyle(fontSize: 16.w),
          //   ),
          //   actions: [
          //     IconButton(
          //       onPressed: () {
          //         Get.toNamed(Routes.startSchedulingPage)?.then((_) {
          //           //刷新数据
          //         });
          //       },
          //       icon: Container(
          //         padding: EdgeInsets.only(
          //           left: 8.w,
          //           right: 8.w,
          //           top: 3,
          //           bottom: 3.w,
          //         ),
          //         decoration: BoxDecoration(
          //           color: Colors.blue,
          //           borderRadius: BorderRadius.all(
          //             Radius.circular(6.r),
          //           ),
          //         ),
          //         child: const Text(
          //           '排班',
          //           style: TextStyle(color: Colors.white),
          //         ),
          //       ),
          //     ),
          //   ],
          //   //     .clickOnce(() {
          //   // 滚轮选择年月↓
          //   //   showModalBottomSheet(
          //   //     context: Get.context!,
          //   //     showDragHandle: true,
          //   //     builder: (context) {
          //   //       return CupertinoDatePicker(
          //   //         minimumDate: DateTime.now().subtract(const Duration(days: 395)),
          //   //         maximumDate: DateTime.now().add(const Duration(days: 365)),
          //   //         mode: CupertinoDatePickerMode.monthYear,
          //   //         initialDateTime: _selectedDate.value,
          //   //         onDateTimeChanged: (date) {
          //   //           print('选择的日期是：$date');
          //   //           // setState(() {
          //   //           _selectedDate.value = date;
          //   //           // });
          //   //         },
          //   //       );
          //   //     },
          //   //   );
          //   // })
          //   backgroundColor: Colors.white,
          //   centerTitle: true,
          // ),
          backgroundColor: const Color(0xffF7FBFE),
          body: _buildBody(),
        );
      },
    );
  }

  Widget _buildBody() {
    return ListView(
      controller: _scrollController,
      physics: const ClampingScrollPhysics(),
      padding: EdgeInsets.all(13.w),
      children: [
        _buildCalendar(),
        AppGaps.vGap10,
        ValueListenableBuilder(
          valueListenable: _dutyList,
          builder: (_, list, __) {
            if (list.isEmpty) return const SizedBox();
            final children = <Widget>[];
            for (final duty in list) {
              children.add(_buildActualDuty(duty));
              children.add(AppGaps.vGap10);
              children.add(_buildPlanDuty(duty));
              children.add(AppGaps.vGap10);
            }
            final first = list.firstOrNull;
            if (first != null) {
              children.add(ValueListenableBuilder(
                valueListenable: _floodCtrl,
                builder: (_, vals, __) {
                  return Wrap(
                      spacing: 5.w,
                      children: _scheduleTime.map<Widget>((item) {
                        return Container(
                          margin: const EdgeInsets.only(bottom: 10),
                          child: Text(
                            item.value!.split(' ')[1],
                            style: TextStyle(
                              fontWeight: FontWeight.w500,
                              color: item.isOnClick ? const Color(0xFF013AF6) : Colors.black,
                              fontSize: 14.sp,
                            ),
                          ),
                        ).clickOnce(() {
                          //点击自己 就不相应
                          if (item.isOnClick) {
                            return;
                          }
                          //其它item.isOnClick 要回复false
                          for (var element in _scheduleTime) {
                            element.isOnClick = false;
                          }
                          //点击那个时间点 那个就掉接口
                          item.isOnClick = !item.isOnClick;
                          getFloodPreventionDataByDuty(first.companyId, '${_selectedDate.value.toDateStr} ${item.value!.split(' ')[1]}');
                        });
                      }).toList());
                },
              ));
              children.add(_buildFloodCtrl(first));
              children.add(AppGaps.vGap10);
            }
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: children,
            );
          },
        ),
        ValueListenableBuilder(
          valueListenable: _majorEvent,
          builder: (_, vals, __) {
            return Column(
              children: vals.map(_buildMajorEvent).joinWith(AppGaps.vGap10),
            );
          },
        ),
        ValueListenableBuilder(
          valueListenable: _floodCtrl,
          builder: (_, vals, __) {
            return Visibility(
              visible: _majorEvent.value.isEmpty && _dutyList.value.isEmpty && _floodCtrl.value.isEmpty,
              child: Container(
                color: Colors.white,
                child: Column(
                  children: [
                    AppGaps.vGap36,
                    SvgPicture.asset('assets/svg/zhiban_empty_bg.svg'),
                    Text(
                      '暂无内容',
                      style: TextStyle(
                        color: const Color(0xFFC7CEE5),
                        fontSize: 14.sp,
                      ),
                    ),
                    AppGaps.vGap40,
                  ],
                ),
              ),
            );
          },
        ),
      ],
    );
  }

  // 获取开始星期，保持今日居中显示
  StartingDayOfWeek _getStartingDayOfWeek() {
    // 获取开始星期
    switch (DateTime.now().weekday) {
      case DateTime.monday:
        return StartingDayOfWeek.friday;
      case DateTime.tuesday:
        return StartingDayOfWeek.saturday;
      case DateTime.wednesday:
        return StartingDayOfWeek.sunday;
      case DateTime.thursday:
        return StartingDayOfWeek.monday;
      case DateTime.friday:
        return StartingDayOfWeek.tuesday;
      case DateTime.saturday:
        return StartingDayOfWeek.wednesday;
      case DateTime.sunday:
        return StartingDayOfWeek.thursday;
      default:
        return StartingDayOfWeek.monday;
    }
  }

  Widget _buildCalendar() {
    final now = DateTime.now();
    return Stack(
      children: [
        // Container(
        //   height: 300.w,
        //   decoration: BoxDecoration(
        //     color: const Color(0xff54B7FD),
        //     borderRadius: BorderRadius.circular(13.w),
        //   ),
        //   alignment: Alignment.topCenter,
        //   child: _buildWeather().paddingSymmetric(vertical: 7.w),
        // ),
        Container(
          // margin: EdgeInsets.only(top: 65.w),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(13.w),
          ),
          child: ValueListenableBuilder(
            valueListenable: _selectedDate,
            builder: (_, date, __) {
              return Column(
                children: [
                  TableCalendar(
                    firstDay: now.subtract(const Duration(days: 365)),
                    // firstDay: now.subtract(const Duration(days: 395)),
                    lastDay: now.add(const Duration(days: 365)),
                    headerStyle: const HeaderStyle(
                      formatButtonVisible: false,
                      titleCentered: true,
                    ),
                    focusedDay: date,
                    // daysOfWeekStyle: DaysOfWeekStyle(
                    //   weekendStyle: TextStyle(
                    //     color: const Color(0xFFEA4C4C),
                    //     fontSize: 14.sp,
                    //   ),
                    //   weekdayStyle: TextStyle(
                    //     color: const Color(0xFF4C4C4C),
                    //     fontSize: 14.sp,
                    //   ),
                    // ),
                    calendarFormat: _calendarFormat,
                    //TableCalendar 的 daysOfWeekStyle 的 dowTextFormatter 属性允许你自定义星期文本的格式。
                    daysOfWeekStyle: DaysOfWeekStyle(
                      dowTextFormatter: (DateTime date, dynamic locale) {
                        // return  date.weekday.toString(); // 返回数字表示的星期
                        final int dayOfWeek = date.weekday;
                        if (dayOfWeek == 1) {
                          return '一';
                        } else if (dayOfWeek == 2) {
                          return '二';
                        } else if (dayOfWeek == 3) {
                          return '三';
                        } else if (dayOfWeek == 4) {
                          return '四';
                        } else if (dayOfWeek == 5) {
                          return '五';
                        } else if (dayOfWeek == 6) {
                          return '六';
                        } else if (dayOfWeek == 7) {
                          return '日';
                        }
                        return dayOfWeek.toString();
                      },
                      weekdayStyle: TextStyle(fontSize: 14.sp, color: const Color(0xFF1D3452)),
                      weekendStyle: TextStyle(fontSize: 14.sp, color: const Color(0xFF1D3452)),
                    ),
                    onPageChanged: _onPageChanged,
                    // 使用自定义的事件指示器构建器
                    calendarBuilders: CustomEventIndicatorBuilder(),
                    eventLoader: _loadEventsForDay,
                    locale: 'zh_CN',
                    calendarStyle: CalendarStyle(
                      selectedDecoration: BoxDecoration(
                        shape: BoxShape.rectangle,
                        borderRadius: BorderRadius.circular(8.w),
                        color: !curry ? const Color(0xFFDCE3FC) : const Color(0xFF1847E3),
                      ),
                      selectedTextStyle: TextStyle(
                        fontWeight: FontWeight.w700,
                        color: !curry ? const Color(0xFF1847E3) : const Color(0xFFFFFFFF),
                        fontSize: 16.sp,
                      ),
                      todayDecoration: BoxDecoration(
                        shape: BoxShape.rectangle,
                        borderRadius: BorderRadius.circular(8.w),
                        color: const Color(0xFFDCE3FC),
                      ),
                      outsideDecoration: const BoxDecoration(shape: BoxShape.rectangle),
                      disabledDecoration: const BoxDecoration(shape: BoxShape.rectangle),
                      //enabledDayPredicate
                      //位于当前选定范围内的日期单元格的装饰。
                      withinRangeDecoration: const BoxDecoration(shape: BoxShape.rectangle),
                      //与“weekendDay”列表匹配的日期单元格的装饰。
                      weekendDecoration: const BoxDecoration(shape: BoxShape.rectangle),
                      //圆角-必要1
                      defaultDecoration: const BoxDecoration(shape: BoxShape.rectangle),
                      //圆角-必要2
                      todayTextStyle: TextStyle(
                        color: const Color(0xFF1847E3),
                        fontWeight: FontWeight.w700,
                        fontSize: 14.sp,
                      ),
                    ),
                    // availableCalendarFormats: const {
                    //   CalendarFormat.month: '周',
                    //   CalendarFormat.twoWeeks: '月',
                    //   CalendarFormat.week: '2 周',
                    // },
                    onDaySelected: (selectedDay, focusedDay) {
                      //isSameDay 是一个方便的方法，用于在处理日期时判断两个日期是否表示同一天。
                      bool istr = false;
                      for (int i = 0; i < eventsList.length; i++) {
                        //只有有事件的日期才可点击
                        if (isSameDay(eventsList[i].date, selectedDay)) {
                          istr = true;
                        }
                      }
                      //只有有事件的日期才可点击
                      if (istr) {
                        curry = true;
                        _selectedDate.value = selectedDay;
                      }
                    },
                    selectedDayPredicate: (day) => isSameDay(date, day),
                    daysOfWeekHeight: 27.w,
                    startingDayOfWeek: _getStartingDayOfWeek(),
                    // onFormatChanged: (format) {
                    //   if (_calendarFormat != format) {
                    //     setState(() {
                    //       _calendarFormat = format;
                    //     });
                    //   }
                    // },
                  ),
                  Padding(
                    padding: EdgeInsets.only(bottom: 10.w, right: 10.w, left: 10.w),
                    child: SvgPicture.asset(
                      _calendarFormat == CalendarFormat.month ? 'assets/svg/table_calendar_up.svg' : 'assets/svg/table_calendar_down.svg',
                    ),
                  ).clickOnce(() {
                    _calendarFormat = _calendarFormat == CalendarFormat.month ? CalendarFormat.week : CalendarFormat.month;
                    setState(() {});
                  }),
                ],
              );
            },
          ),
        ),
      ],
    );
  }

  // Widget _buildWeather() {
  //   return Row(
  //     mainAxisAlignment: MainAxisAlignment.center,
  //     children: [
  //       SizedBox(
  //         width: 143.w,
  //         child: Row(
  //           mainAxisAlignment: MainAxisAlignment.end,
  //           children: [
  //             Text(
  //               '值班当日天气',
  //               style: TextStyle(fontSize: 14.w, color: Colors.white),
  //             ),
  //             AppGaps.hGap6,
  //             SvgPicture.asset(
  //               _weather['textDay']._weatherIcon,
  //               width: 37.w,
  //               height: 37.w,
  //             ),
  //           ],
  //         ),
  //       ),
  //       AppGaps.hGap10,
  //       Container(
  //         height: 17.w,
  //         width: 2.w,
  //         decoration: const BoxDecoration(
  //           gradient: LinearGradient(
  //             colors: [
  //               Color(0x00ffffff),
  //               Color(0xffffffff),
  //               Color(0x00ffffff),
  //             ],
  //             begin: Alignment.topCenter,
  //             end: Alignment.bottomCenter,
  //           ),
  //         ),
  //       ),
  //       AppGaps.hGap10,
  //       SizedBox(
  //         width: 156.w,
  //         child: Row(
  //           children: [
  //             Text(
  //               _weather['tempMax'] ?? '未知',
  //               style: TextStyle(
  //                 fontSize: 37.w,
  //                 color: Colors.white,
  //                 fontWeight: FontWeight.w500,
  //               ),
  //             ),
  //             AppGaps.hGap6,
  //             Column(
  //               crossAxisAlignment: CrossAxisAlignment.start,
  //               mainAxisAlignment: MainAxisAlignment.center,
  //               mainAxisSize: MainAxisSize.min,
  //               children: [
  //                 Text(
  //                   '/${_weather['tempMin']}℃',
  //                   style: TextStyle(fontSize: 11.w, color: Colors.white),
  //                 ),
  //                 Text(
  //                   '${_weather['textDay']}转${_weather['textNight']} / ${_weather['windDirDay']}',
  //                   style: TextStyle(fontSize: 11.w, color: Colors.white),
  //                 ),
  //               ],
  //             ),
  //           ],
  //         ),
  //       ),
  //     ],
  //   );
  // }

  Widget _buildActualDuty(DutyMgmtDayEntity duty) {
    return _card(
      '实际值班人：${duty.actualDutyPerson} / ${duty.actualDutyPersonPhone ?? ''}',
      Column(
        children: [
          _textRow('职位：', duty.actualDutyPersonPosition ?? '未知'),
          _textRow('部门：', duty.actualDutyPersonDept ?? '未知'),
          _textRow('上岗时间：', duty.onDutyTime ?? '未知'),
          _textRow('离岗时间：', duty.offDutyTime ?? '未知'),
          _textRow('班次名称：', duty.scheduleName ?? '未知'),
          _textRow('值班领导：', duty.actualDutyLeader ?? '未知'),
          _textRow('值班领导电话：', duty.actualDutyLeaderPhone ?? '未知', isCall: true)
        ],
      ),
    );
  }

  Widget _buildPlanDuty(DutyMgmtDayEntity duty) {
    return _card(
      '计划值班人：${duty.planDutyPerson} / ${duty.planDutyPersonPhone}',
      Column(
        children: [
          _textRow('职位：', duty.planDutyPersonPosition ?? '未知'),
          _textRow('部门：', duty.planDutyPersonDept ?? '未知'),
          _textRow('班次名称：', duty.scheduleName ?? '未知'),
          _textRow('值班领导：', duty.planDutyLeader ?? '未知'),
          _textRow('值班领导电话：', duty.planDutyLeaderPhone ?? '未知', isCall: true),
        ],
      ),
    );
  }

  Widget _buildMajorEvent(MajorEventEntity event) {
    return _card(
      '重大事件',
      Column(
        children: [
          _textRow('事件发生时间：', event.eventTime),
          _textRow('事件发生地点：', event.eventAddr),
          _textRow('事件描述：', event.eventDesc),
          _textRow('事件原因：', event.eventReason),
          _textRow('处置措施：', event.measure),
          _textRow(
              '处置方式：', //	处置方式(1销警2处置)
              switch (event.measureWay) {
                1 => '销警',
                2 => '处置',
                _ => '未知',
              }),
          _textRow('备注：', event.remark),
        ],
      ),
    );
  }

  Widget _buildFloodCtrl(DutyMgmtDayEntity duty) {
    return ValueListenableBuilder(
      valueListenable: _floodCtrl,
      builder: (_, vals, __) {
        print('_floodCtrl.value: ${_floodCtrl.value}');
        return _floodCtrl.value.isNotEmpty
            ? _card(
                '防汛重点部位数据信息',
                // Column(
                //   children: _floodCtrl.value
                //       .map((e) => _floodCard(
                //             e.reservoir,
                //             rain: e.rainfall,
                //             water: e.waterLevel,
                //             main: e.mainDamBeachDistance,
                //             sub: e.subDamBeachDistance,
                //           ))
                //       .toList(),
                // )
                Column(
                  children: _floodCtrl.value
                      .map(
                        (e) => Column(
                          children: [
                            Row(
                              children: [
                                Text(
                                  '${e.companyName}',
                                  style: TextStyle(
                                    fontSize: 14.w,
                                    color: const Color(0xff1D3452),
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                                AppGaps.hGap14,
                                Text(
                                  '${e.systemName}',
                                  style: TextStyle(
                                    fontSize: 14.w,
                                    color: const Color(0xff1D3452),
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              ],
                            ),
                            Wrap(
                                spacing: 5.w,
                                children: e.floodPreventionDataVOS!.map<Widget>((item) {
                                  return Padding(
                                    padding: EdgeInsets.symmetric(vertical: 3.w),
                                    child: Row(
                                      children: [
                                        Text(
                                          '${item.monitoringItems}:',
                                          style: TextStyle(
                                            fontSize: 13.w,
                                            color: const Color(0xffC7CEE5),
                                          ),
                                        ),
                                        Text(
                                          ':${item.value}',
                                          style: TextStyle(
                                            fontSize: 13.w,
                                            color: const Color(0xff1D3452),
                                          ),
                                        ),
                                        AppGaps.hGap14,
                                        Text(
                                          '设备名称:',
                                          style: TextStyle(
                                            fontSize: 13.w,
                                            color: const Color(0xffC7CEE5),
                                          ),
                                        ),
                                        Text(
                                          '${item.deviceName}',
                                          style: TextStyle(
                                            fontSize: 13.w,
                                            color: const Color(0xff1D3452),
                                          ),
                                        ),
                                      ],
                                    ),
                                  );
                                }).toList()),
                          ],
                        ),
                      )
                      .toList(),
                ),
              )
            : _card(
                '防汛重点部位数据信息',

                // _floodCard(
                //   '未知位置',
                //   rain: 0,
                //   water: 0,
                //   main: 0,
                //   sub: 0,
                // ),
                Container(
                  color: Colors.white,
                  child: Column(
                    children: [
                      AppGaps.vGap36,
                      SvgPicture.asset('assets/svg/zhiban_empty_bg.svg'),
                      Text(
                        '暂无内容',
                        style: TextStyle(
                          color: const Color(0xFFC7CEE5),
                          fontSize: 14.sp,
                        ),
                      ),
                      AppGaps.vGap40,
                    ],
                  ),
                ),
              );
      },
    );
  }

  Widget _floodCard(
    String? title, {
    int? rain,
    int? water,

    /// 主坝干滩距离
    int? main,

    /// 副坝干滩距离
    int? sub,
  }) {
    final nullCount = [rain, water, main, sub].fold(0, (p, e) => p + (e == null ? 1 : 0));
    if (nullCount == 4) return const SizedBox();
    final doubleRow = nullCount > 2;
    final height = doubleRow ? 114.w : 87.w;
    return Stack(
      alignment: Alignment.center,
      children: [
        SizedBox(
          width: 311.w,
          height: height,
        ),
        Positioned(
          top: 0,
          left: 0,
          child: Container(
            width: 165.w,
            height: 50.w,
            decoration: BoxDecoration(
              color: const Color(0xff1847E3),
              borderRadius: BorderRadius.circular(6.w),
            ),
          ),
        ),
        Positioned(
          left: 13.w,
          top: 4.7.w,
          child: Text(
            title ?? '未知位置',
            style: TextStyle(
              color: Colors.white,
              fontSize: 16.w,
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
        SizedBox(
          width: 311.w,
          height: 87.w,
          child: CustomPaint(
            painter: _FloodCardPaint(
              bezierCenterX: 27.w + (title?.length ?? 4) * 16.w,
              radius: 13.w,
              cornerHeight: 32.w,
            ),
          ),
        ),
        Positioned(
          left: 0,
          bottom: 0,
          child: Wrap(
            children: [
              if (rain != null) _floodItem('降雨量', rain),
              if (water != null) _floodItem('水位', water),
              if (main != null) _floodItem('主干流距离', main),
              if (sub != null) _floodItem('支流距离', sub),
            ],
          ),
        ),
      ],
    );
  }

  Widget _floodItem(String title, int val) {
    final String? icon = switch (title) {
      '降雨量' => Assets.svgFloodCtrlRain,
      '水位' => Assets.svgFloodCtrlWater,
      '主干流距离' => Assets.svgFloodCtrlBank,
      '支流距离' => Assets.svgFloodCtrlBank,
      _ => null,
    };
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 5.w, vertical: 13.w),
      child: Row(
        children: [
          if (icon != null) SvgPicture.asset(icon, height: 16.w, width: 16.w),
          AppGaps.hGap2,
          Text(
            title,
            style: TextStyle(
              color: const Color(0xff6C779C),
              fontSize: 11.w,
            ),
          ),
          Text(
            val.toString(),
            style: TextStyle(
              color: const Color(0xff1847E3),
              fontSize: 11.w,
            ),
          ),
        ],
      ),
    );
  }

  Widget _card(String title, Widget content) {
    return CustomCardX(
      padding: EdgeInsets.all(16.w),
      titleWidget: Row(
        children: [
          SvgPicture.asset(Assets.svgIconBlueStar, height: 13.w, width: 13.w),
          AppGaps.hGap10,
          Expanded(
            child: Text(
              title,
              style: TextStyle(
                fontSize: 16.w,
                color: const Color(0xff1D3452),
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ],
      ),
      divider: CustomCardX.builtinDividerWithPadding,
      child: content,
    );
  }

  /// isCall: 是否是拨打电话
  Widget _textRow(String title, String content, {bool isCall = false}) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 3.w),
      child: Row(
        children: [
          Text(
            title,
            style: TextStyle(
              color: const Color(0xffC7CEE5),
              fontSize: 13.w,
            ),
          ),
          Expanded(
            child: !isCall
                ? Text(
                    content,
                    style: TextStyle(
                      color: const Color(0xff1D3452),
                      fontSize: 13.w,
                    ),
                  )
                : InkWell(
                    child: Text(
                      content,
                      style: TextStyle(
                        color: const Color(0xff0223f6),
                      ),
                    ),
                    onTap: () {
                      launchUrlString('tel:$content');
                    }),
          ),
        ],
      ),
    );
  }

  /// 刷新
  void _refresh() async {
    _majorEvent.value.clear();
    await _getDutyList(_selectedDate.value.toDateStr);
    final majorEventIds = <String>[];
    for (final duty in _dutyList.value) {
      final id = duty.majorEventInfoId;
      if (id != null) majorEventIds.add(id);
    }
    if (majorEventIds.isNotEmpty) {
      await _getMajorEvent(majorEventIds);
    } else {
      //majorEventIds为空时 需要清楚数据
      _majorEvent.value.clear();
    }
  }

  ///切换页面回调
  void _onPageChanged(DateTime currentDate) async {
    curry = true;
    print('_onPageChanged${currentDate}');
    // 在切换页面后，重新加载当前月份的事件
    eventsList = await _loadEventsForCurrentMonth(currentDate);
    if (eventsList.isNotEmpty && _calendarFormat != CalendarFormat.week) {
      //有事件 就使用第一个事件
      _selectedDate.value = eventsList.first.date;
    } else {
      //没事件 就currentDate
      _selectedDate.value = currentDate;
    }
  }

  // int hdMonth = DateTime.now().month;

  ///加载当前'月份'的事件
  Future<List<EventModel>> _loadEventsForCurrentMonth(DateTime month) async {
    // if (hdMonth == month.month) {
    //   return [];
    // }
    // hdMonth = month.month;
    print('_loadEventsForCurrentMonth${month}');
    // 这里模拟了一个异步加载事件的过程
    // await Future.delayed(const Duration(seconds: 1)); // 模拟延迟加载 这里放开不知道为啥 在前后快速滑动日历时会一直回调_onPageChanged
    return getMonthEvent(month);
  }

  Future<List<EventModel>> getMonthEvent(DateTime month) async {
    final List<EventModel> events = [];

    /// 获得1个月的事件
    final resp = await HttpUtil().generateGetRequest<List<MonthDutyDateEntity>>(
      '${Interface.mainBaseUrl}/admin-api/system/duty-record-info/recordStatsByMonth',
      queryParameters: {
        'queryMonth': '${month.year}-${month.month.toString().padLeft(2, '0')}',
        'companyId': UserManager.getUserCompanyId(),
      },
    ).execute();
    if (resp.isSucceed && resp.data != null) {
      final List<MonthDutyDateEntity> list = resp.data!;
      for (int i = 0; i < list.length; i++) {
        final split = list[i].dutyDate.split('-');
        if (split.length == 3) {
          events.add(EventModel(title: list[i].count, date: DateTime(int.parse(split[0]), int.parse(split[1]), int.parse(split[2]))));
        }
      }

      ///判断eventsList中的数据是否等于events
      // if (eventsList.isNotEmpty&&events.isNotEmpty&&eventsList.length == events.length&&events.first.date==eventsList.first.date) {
      //   events.clear();
      // }
      // 从你的数据源加载事件，这里只是示例
      // if (month.month == 5) {
      //   events = [
      //     EventModel(title: "Meeting", date: DateTime(2024, 5, 11)),
      //     EventModel(title: "Birthday Party", date: DateTime(2024, 5, 12)),
      //     EventModel(title: "Project Deadline", date: DateTime(2024, 5, 13)),
      //     EventModel(title: "Project Deadline1", date: DateTime(2024, 5, 14)),
      //   ];
      // } else if (month.month == 4) {
      //   events = [
      //     EventModel(title: "Meeting", date: DateTime(2024, 4, 11)),
      //     EventModel(title: "Birthday Party", date: DateTime(2024, 4, 12)),
      //     EventModel(title: "Project Deadline", date: DateTime(2024, 4, 13)),
      //     EventModel(title: "Project Deadline1", date: DateTime(2024, 4, 14)),
      //   ];
      // } else if (month.month == 6) {
      //   events = [
      //     EventModel(title: "Meeting", date: DateTime(2024, 6, 11)),
      //     EventModel(title: "Birthday Party", date: DateTime(2024, 6, 12)),
      //     EventModel(title: "Project Deadline", date: DateTime(2024, 6, 13)),
      //     EventModel(title: "Project Deadline1", date: DateTime(2024, 6, 14)),
      //   ];
      // }
    }
    return events;
  }
}

/// 自定义事件指示器
class CustomEventIndicatorBuilder extends CalendarBuilders {
  CustomEventIndicatorBuilder()
      : super(
          markerBuilder: (context, date, events) {
            print('context, date, events---$date---$events');
            return events.isNotEmpty
                ? Transform.translate(
                    offset: const Offset(0, 15), // 偏移15像素到下方
                    child: Container(
                      width: 5,
                      decoration: const BoxDecoration(
                        shape: BoxShape.circle,
                        color: Color(0xFF0EB273),
                        //当前事件 设置color(是今天就设置0xFF1847E3)
                        // color: isSameDay(date, DateTime.now()) ?const Color(0xFF1847E3):const Color(0xFF0EB273),
                      ),
                    ),
                  )
                : Container(
                    margin: EdgeInsets.all(5.w),
                    decoration: BoxDecoration(
                      shape: BoxShape.rectangle,
                      //当前事件排除设置color(是今天就设置透明)
                      color: isSameDay(date, DateTime.now()) ? Colors.transparent : const Color(0xFFF6F8FF).withOpacity(0.5),
                      borderRadius: BorderRadius.all(
                        Radius.circular(8.w),
                      ),
                    ),
                  );
            // if (_loadEventsForDay(date).isNotEmpty) {
            //   return Transform.translate(
            //     offset: const Offset(0, 15), // 偏移15像素到下方
            //     child: Container(
            //       width: 5,
            //       decoration: const BoxDecoration(
            //         shape: BoxShape.rectangle,
            //         color: Color(0xFF0EB273), // 更改颜色为你想要的
            //       ),
            //     ),
            //   );
            // }
            // return Container();
          },
          // selectedBuilder: (context, date, holiday) {
          //   List<EventModel> events = _loadEventsForDay(date);
          //   bool hasEvent = events.isNotEmpty;
          //   return Padding(
          //     padding: const EdgeInsets.all(4.0),
          //     child: Material(
          //       child: InkWell(
          //         onTap: hasEvent ? null : () {}, // 如果没有事件，禁止点击
          //         child: Center(
          //           child: Text(
          //             date.day.toString(),
          //             style: TextStyle(
          //               color: hasEvent ? Colors.black : Colors.grey, // 根据是否有事件调整颜色
          //               fontSize: 16,
          //             ),
          //           ),
          //         ),
          //       ),
          //     ),
          //   );
          // },
        );
}

/// 事件模型
class EventModel {
  EventModel({required this.title, required this.date});

  final String title;
  final DateTime date;
}
